package cn.itguy.mobileguard.activity;

import cn.itguy.mobileguard.IMGPreferences;
import cn.itguy.mobileguard.R;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class SetPasswordActivity extends BaseActivity {

	private Button   btn_commit;
	private EditText et_psw_original;
	private EditText et_psw;
	private EditText et_psw_confirm;
	
	private IMGPreferences preferences;
	
	private String password;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.set_password);
		
		((TextView) findViewById(R.id.tv_title)).setText(R.string.titleText_setPsw);
		
		Button btn_back = (Button) findViewById(R.id.btn_left);
		btn_back.setVisibility(View.VISIBLE);
		btn_back.setOnClickListener(this);
		
		btn_commit      = (Button)   findViewById(R.id.btn_commit);
		btn_commit.setOnClickListener(this);
		
		et_psw          = (EditText) findViewById(R.id.et_psw);
		et_psw_confirm  = (EditText) findViewById(R.id.et_psw_confirm);
		et_psw_original = (EditText) findViewById(R.id.et_psw_original);
		
		preferences = IMGPreferences.getInstance(this);
		password = preferences.getPassword();
		if(!TextUtils.isEmpty(password)) {
			((TextView) findViewById(R.id.tv_pwd_label)).setText(R.string.labelText_new_pwd);
			findViewById(R.id.tv_pwd_ori_label).setVisibility(View.VISIBLE);
			et_psw_original.setVisibility(View.VISIBLE);
		}
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_left:
			finish();
			break;
		case R.id.btn_commit:
			doCommit();
			break;
		}
	}

	/**
	 * do commit password work.
	 */
	private void doCommit() {
		if(!TextUtils.isEmpty(password)) {
			if(!TextUtils.equals(et_psw_original.getText(), password)) {
				et_psw_original.setError(getString(R.string.tipText_password_original_error));
				return;
			}
		}
		if(et_psw.getText().length() < 6 || et_psw.getText().length() > 10) {
			et_psw.setError(getString(R.string.tipText_password_length_error));
			return;
		}
		if(!TextUtils.equals(et_psw.getText(), et_psw_confirm.getText())) {
			et_psw_confirm.setError(getString(R.string.tipText_password_confirm_error));
			return;
		}
		preferences.setPassword(et_psw_confirm.getText().toString());
		Toast.makeText(this, R.string.tipText_password_success, Toast.LENGTH_SHORT).show();
		finish();
	}

}
